package whf.framework.tools.generator.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import whf.framework.tools.generator.cfg.Config;

/**
 * @author wanghaifeng
 *
 */
public class MysqlTableGetter extends AbstractTableGetter {

	private static Log log = LogFactory.getLog(MysqlTableGetter.class);
	
	private List<String> tableComments = new ArrayList<String>();

	public MysqlTableGetter(Config config) {
		super(config);
	}
	
	/* (non-Javadoc)
	 * @see whf.framework.tools.generator.db.AbstractTableGetter#getTables()
	 */
	public List<Table> getTables() throws Exception {
		if (StringUtils.isEmpty(super.config.getTables()) || StringUtils.equalsIgnoreCase("all", super.config.getTables())) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			StringBuffer sb = new StringBuffer();
			try {
				con = super.getConnection();
				pstmt = con.prepareStatement("select table_name,table_comment from tables where table_type='base table' and table_schema=?");
				pstmt.setString(1, super.config.getSchema());
				rs = pstmt.executeQuery();
				while (rs.next()) {
					String tableName = rs.getString(1);
					sb.append(tableName).append(",");
					this.tableComments.add(rs.getString(2));
				}
			} finally {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (con != null)
					con.close();
			}
			config.setTables(sb.toString());
		}
		return getTables(super.config.getTables());
	}

	/* (non-Javadoc)
	 * @see whf.framework.tools.generator.db.AbstractTableGetter#getTables(java.lang.String)
	 */
	public List<Table> getTables(String tableNames) throws Exception {
		log.info("正准备输出表:"+tableNames);
		String[] tables = StringUtils.split(tableNames, ",");
		List<Table> list = new ArrayList<Table>();
		for (int i = 0; tables != null && i < tables.length; i++) {
			String tableComment = "";
			if(i < this.tableComments.size()){
				tableComment = this.tableComments.get(i);
			}
			list.add(new MysqlTable(super.getConnectionManager(), super.config.getSchema(), tables[i].trim(),
					super.config.getTablePrefix(), tableComment));
		}
		return list;
	}
}
